package main

import (
	"flag"
	"io"
	"os"

	"kratos-shop/internal/conf"

	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/config/file"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/go-kratos/kratos/v2/transport/http"

	_ "go.uber.org/automaxprocs"
)

// go build -ldflags "-X main.Version=x.y.z"
var (
	// Name is the name of the compiled software.
	Name string
	// Version is the version of the compiled software.
	Version string
	// flagconf is the config flag.
	flagconf string

	id, _ = os.Hostname()
)

func init() {
	flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func newApp(logger log.Logger, gs *grpc.Server, hs *http.Server) *kratos.App {
	return kratos.New(
		kratos.ID(id),
		kratos.Name(Name),
		kratos.Version(Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(logger),
		kratos.Server(
			gs,
			hs,
		),
	)
}

func main() {
	flag.Parse()
	/*
		日志全局配置，代码中真正使用的，一般是 log.Helper 方法
		logger 直接使用，需要输入日志级别: 	logger.Log(log.LevelInfo,"开始初始化")
		使用了 help 方法以后，直接用就可以了： 	log.NewHelper(logger).Info("开始初始化")
	*/
	// 输出到 ./test.log 文件
	f, err := os.OpenFile("test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return
	}
	// 如果将日志直接打印到控制台上，直接，f=os.Stdout 即可
	// 将日志，同时打印到控制台和终端， 注意，这里的 io 和 os 这两个标准库，有所不同，os负责从哪里来，io 负责怎么传？
	l := log.NewStdLogger(io.MultiWriter(f, os.Stdout))
	logger := log.With(l,
		"ts", log.DefaultTimestamp,
		"caller", log.DefaultCaller,
		"service.id", id,
		"service.name", Name,
		"service.version", Version,
		"trace.id", tracing.TraceID(),
		"span.id", tracing.SpanID(),
	)
	//通过 kratos 提供的 log.FilterKey 方法进行日志脱敏，比如密码和电话号码等
	log.NewHelper(log.NewFilter(logger, log.FilterKey("password"))).Infow("msg", "记录用户的登录信息", "password", "1888888888")

	c := config.New(
		config.WithSource(
			file.NewSource(flagconf),
		),
	)
	defer c.Close()

	if err := c.Load(); err != nil {
		panic(err)
	}

	var bc conf.Bootstrap
	if err := c.Scan(&bc); err != nil {
		panic(err)
	}

	app, cleanup, err := wireApp(bc.Server, bc.Data, logger)
	if err != nil {
		panic(err)
	}
	defer cleanup()

	// start and wait for stop signal
	if err := app.Run(); err != nil {
		panic(err)
	}
}
